﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Shop.Base.Entity;
using Shop.Base.Entity.Delete;
using Shop.Base.Entity.Insert;
using Shop.Base.Entity.Select;
using Shop.Base.Entity.Update;
using Shop.Base.Interface;
using Shop.Entity;
using Shop.Tools;
using Shop.Web.Models;

namespace Shop.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class SystemMenuController : Controller
    {
        // GET
        private IMapper mapper;
        private ISystemMenu menu;
        private ISystemMenuButton menuButton;
        private ISystemButton button;

        public SystemMenuController(IMapper mapper, ISystemMenu _menu,ISystemMenuButton _menuButton, ISystemButton _button)
        {
            this.mapper = mapper;
            this.menu = _menu;
            this.menuButton = _menuButton;
            this.button = _button;
        }
        public IActionResult Index()
        {
            ViewBag.allMenu = AllMenus();
            return View();
        }

        [HttpGet]
        public IActionResult GetList(string name, Guid? parentId, int isDel = -1, int pageIndex = 1, int pageSize = 15)
        {
            try
            {
                var list = menu.GetPage(name, parentId, isDel, pageIndex, pageSize, out int total);
                var showList = mapper.Map<List<SystemMenuPo>, List<ShowSystemMenu>>(list);
                if (showList.Any())
                {
                    var all = menu.GetAll();
                    showList.ForEach(x =>
                    {
                        if (all.Any(c => c.Id == x.ParentId))
                        {
                            x.ParentName = all.FirstOrDefault(c => c.Id == x.ParentId).MemuName;
                        }
                    });
                }
                return Json(new ResultModel
                {
                    code = OperationResultType.GetList,
                    data = new { list = showList, total },
                    error_msg = "",
                    success = true
                });
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                return Json(new ResultModel { code = OperationResultType.Throws, data = new List<string>(), error_msg = "查询异常", success = false });
            }
        }

        public IActionResult Edit(Guid? menuId)
        {
            var comUser = HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
            if (menuId.HasValue && !menuId.Value.IsEmptyGuid())
            {
                var menus = menu.Find<SystemMenuPo>(menuId.Value);
                menus.UpdateId = comUser.Id;
                menus.UpdateName = comUser.UserName;
                menus.UpdateAt = DateTime.Now;
                ViewBag.model = menus.ToJsonData();
            }
            else
            {
                ViewBag.model = new AddSystemMenu { CreateId = comUser.Id, CreateName = comUser.UserName }.ToJsonData();
            }
            ViewBag.allMenu = AllMenus();
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit([FromForm]SystemMenuPo model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var comUser = HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
                    if (model.Id.IsEmptyGuid())
                    {
                        var inserts = mapper.Map<SystemMenuPo, AddSystemMenu>(model);
                        menu.Insert(inserts, comUser);
                    }
                    else
                    {
                        var updates = mapper.Map<SystemMenuPo, UpdateSystemMenu>(model);
                        menu.Update(updates, comUser);
                    }
                    return RedirectToAction("Index");
                }
                ViewBag.model = model.ToJsonData();
                TempData["errMsg"] = new JsMessage("无效的操作", 5, JsMessageType.Warning).ToString();
                ViewBag.allMenu = AllMenus();
                return View();
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                ViewBag.model = model.ToJsonData();
                ViewBag.allMenu = AllMenus();
                if (e.Message.Contains("#"))
                    TempData["errMsg"] = new JsMessage(e.Message.Replace("#", ""), 5, JsMessageType.Warning).ToString();
                else
                    TempData["errMsg"] = new JsMessage("保存出现异常", 5, JsMessageType.Danger).ToString();
                return View();
            }
        }

        [HttpPost]
        public IActionResult Delete(Guid id)
        {
            try
            {
                if (id.IsEmptyGuid()) return Json(new ResultModel { code = OperationResultType.ParamError, error_msg = "指定删除的菜单不存在", success = false });
                var comUser = HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
                menu.Delete<UpdateSystemMenu>(id, comUser);
                return Json(new ResultModel { code = OperationResultType.Success, error_msg = "删除成功", success = true });
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                return Json(new ResultModel { code = OperationResultType.Throws, error_msg = "系统异常，请刷新再试", success = false });
            }
        }

        private string AllMenus(bool isdel=false)
        {
            var allMenu = menu.GetAll();
            if (allMenu.Any())
            {
                if (isdel)
                    return JsonConvert.SerializeObject(allMenu.Select(x => new { label = x.MemuName, value = x.Id }));
                return JsonConvert.SerializeObject(allMenu.Where(x=>x.IsDel==false).Select(x => new { label = x.MemuName, value = x.Id }));
            }
            return allMenu.ToJsonData();
        }
        
        //给菜单设置按钮
        public IActionResult SetButton(Guid menuId)
        {
            if (menuId.IsEmptyGuid()) return RedirectToAction("Index");
            var saved = menuButton.GetAll(menuId);
            var saveList = mapper.Map<List<SystemMenuButtonPo>, List<ShowSystemMenuButton>>(saved);
            var allbutton = button.GetAll<SystemButtonPo>();
            allbutton.ForEach(x =>
            {
                if (!saveList.Any(c => c.ButtonId == x.Id))
                {
                    saveList.Add(new ShowSystemMenuButton
                    {
                        ButtonId = x.Id,
                        ButtonName = x.ButtonName,
                        Icons = x.Icons,
                        MenuId = menuId,
                        Titles = x.Titles,
                        IsSelected = false
                    });
                }
            });
            ViewBag.list = CompareList(saveList, menuId);
            ViewBag.menuId = menuId;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult SetButton(List<ShowSystemMenuButton> list, Guid menuId)
        {
            if (menuId.IsEmptyGuid()) return RedirectToAction("Index");
            try
            {
                if (ModelState.IsValid)
                {
                    list = list.Where(x => x.IsSelected).ToList();
                    var lists = mapper.Map<List<ShowSystemMenuButton>, List<AddSystemMenuButton>>(list);
                    menuButton.MultSave(lists);
                    return RedirectToAction("Index");
                }
            }
            catch (Exception e)
            {
                Tools.StaticConst.log.Error(e);
                TempData["errMsg"] = new JsMessage("保存出现异常", 5, JsMessageType.Danger).ToString();
            }
            ViewBag.list = CompareList(list, menuId);
            ViewBag.menuId = menuId;
            return View();
        }

        private string CompareList(List<ShowSystemMenuButton> saveList,Guid menuId)
        {
            var allbutton = button.GetAll<SystemButtonPo>();
            allbutton.ForEach(x =>
            {
                if (!saveList.Any(c => c.ButtonId == x.Id))
                {
                    saveList.Add(new ShowSystemMenuButton
                    {
                        ButtonId = x.Id,
                        ButtonName = x.ButtonName,
                        Icons = x.Icons,
                        MenuId = menuId,
                        Titles = x.Titles,
                        IsSelected = true,
                        SourceName = x.ButtonName
                    });
                }
                else
                {
                    var mo = saveList.Find(c => c.ButtonId == x.Id);
                    mo.SourceName = x.ButtonName;
                }
            });
            return saveList.ToJsonData();
        }
    }
}